package cn.cerc.sample.config;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import cn.cerc.db.core.ISession;
import cn.cerc.db.core.Utils;
import cn.cerc.db.redis.Redis;
import cn.cerc.mis.core.AppClient;
import cn.cerc.mis.core.IAppLogin;
import cn.cerc.mis.core.IForm;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class AppLogin implements IAppLogin {

    @Override
    public String getLoginView(IForm form) {
        String userCode = form.getRequest().getParameter("login_usr");
        String password = form.getRequest().getParameter("login_pwd");

        form.getRequest().setAttribute("login_usr", form.getSession().getUserCode());
        if (Utils.isEmpty(userCode) && Utils.isEmpty(password))
            return "login.jsp";

        log.info("userCode {}, password {}", userCode, password);
        if (!form.getSession().getUserCode().equals(userCode) || !"123456".equals(password)) {
            form.getRequest().setAttribute("msg", "帐号或密码错误");
            return "login.jsp";
        }

        final String token = Utils.getGuid();
        AppClient client = new AppClient(form.getRequest(), form.getResponse());
        try (Redis redis = new Redis()) {
            redis.hset(client.key(), ISession.TOKEN, token);
        }
        form.getSession().loadToken(token);
        return null;
    }

}
